package org.uiot.protocol.codec

import org.grails.testing.GrailsUnitTest
import spock.lang.Specification

class CodecRuleSpec extends Specification implements GrailsUnitTest {

    final static groovyLoader = new GroovyClassLoader()

    def setup() {
    }

    def cleanup() {
    }

    void "test as CachedRule"() {
        given:
        def original = 5
        def rule = new CodecRule(
                code               : "test", name: "test", endian: CodecTraits.ENDIAN.LITTLE, length: 8,
                lengthUnit         : CodecTraits.LengthUnit.Bit, type: CodecTraits.Type.Numeric,
                encodingScript: "x * 10", decodingScript: "x * 0.1", placeholder: null
        )

        when:
        def cache = rule as CachedRule

        then:
        ["code", "name", "endian", "length", "lengthUnit", "type"].find {
            rule[it] != cache[it]
        } == null

        when:
        def script1 = groovyLoader.parseClass(rule.encodingScript).newInstance() as Script
        def script2 = cache.encodingScriptClass.newInstance() as Script
        script1.binding.setVariable("x", original)
        script2.binding.setVariable("x", original)

        then:
        script1.run() == script2.run()

        when:
        def script3 = groovyLoader.parseClass(rule.decodingScript).newInstance() as Script
        def script4 = cache.decodingScriptClass.newInstance() as Script
        script3.binding.setVariable("x", original)
        script4.binding.setVariable("x", original)

        then:
        script3.run() == script4.run()
    }
}